<template>
  <el-dialog title="登陆 | 注册" customClass="fitWidth" v-model="showLogin" center :before-close="cancelLogin"
    @closed="goBack()">
    <el-dialog v-model="showVerifyCode" width="30%" title="输入验证码" append-to-body>
    </el-dialog>

    <el-form :model="form" ref="loginFormRef" :rules="rules" size="mini">
      <el-form-item label="账号" prop="username">
        <el-input v-model="form.username" autocomplete="off" placeholder="邮箱或手机号" clearable></el-input>
      </el-form-item>
      <el-form-item label="密&emsp;码" prop="password">
        <el-input v-model="form.password" placeholder="6~20位长度" show-password></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="submitForm()" :loading="loading" :disabled="loading">登 陆</el-button>
        <el-button type="primary" @click="submitForm((login = false))" :loading="loading" :disabled="loading">注
          册</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { ref, reactive } from "vue";
import { useStore } from "vuex";
import { useRoute } from "vue-router";
import { ApiGetToken, ApiAddUser } from "@/http/api";
import { ElMessage, ElMessageBox } from "element-plus";
import { setToken, goTo } from "@/libs/utils";

export default {
  setup() {
    const store = useStore();
    const route = useRoute();
    if (store.state.token && store.state.userInfo) {
      ElMessage.warning("你已登录!");
      goTo(route.query.redirect || "/");
    }
    const showLogin = ref(true);
    const showVerifyCode = ref(false);
    const loginFormRef = ref();
    const loading = ref(false);
    const goBack = () => {
      showLogin.value = false;
      showVerifyCode.value = false;
      goTo(route.query.redirect || "/");
    };
    const cancelLogin = () => {
      ElMessage.warning("取消登陆!");
      goTo();
    };
    function submitForm(login = true) {
      let validForm = true;
      loginFormRef.value.validate((valid) => {
        if (!valid) validForm = false;
      });
      if (validForm) {
        loading.value = true;
        if (login) {
          //登陆
          ApiGetToken({
            username: form.username,
            password: form.password,
          }).then((res) => {
            loading.value = false;
            if (res.code === 2000) {
              ElMessage.success("登录成功!");
              setToken(store, res.data.token);
              goBack();
            } else {
              console.log("登陆错误:", res);
              ElMessage.error(res.message);
            }
          }).catch(err => {
            loading.value = false;
            console.log("login failed", err)
          });
        } else {
          let phone = null;
          let email = null;
          if (/^1[3456789]\d{9}$/.test(form.username)) {
            phone = form.username;
          } else if (
            /^\w+((.\w+)|(-\w+))@[A-Za-z0-9]+((.|-)[A-Za-z0-9]+).[A-Za-z0-9]+$/.test(
              form.username
            )
          ) {
            email = form.username;
          } else {
            ElMessage.error("用户名不是合法的手机号或邮箱号!");
            return;
          }
          //注册
          let extra = phone ? { phone } : { email };
          let formData = {
            nickname: form.username,
            password: form.password,
            ...extra,
          };
          ApiAddUser(formData).then((res) => {
            loading.value = false;
            if (res.code === 2000) {
              setToken(store, res.data.token);
              ElMessage.success("注册成功!");
              goBack();
            } else if (res.code === 1004) {
              ElMessage.info(res.message);
              submitVerifyCode(formData);
            } else {
              ElMessage.error(`注册出错:${res.message}`);
              console.log("ApiAddUser Error:", res);
            }
          });
        }
      }
    }

    const submitVerifyCode = (formData) => {
      ElMessageBox.prompt("请输入你收到的验证码", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPattern: /^\d{6}$/,
        inputErrorMessage: "验证码格式不正确",
      }).then(({ value }) => {
        ApiAddUser({ ...formData, code: value }).then((res) => {
          if (res.code === 2000) {
            ElMessage.success("注册成功!");
            setToken(store, res.data.token);
            goBack();
          } else {
            ElMessage.error(res.message);
          }
        });
      });
    };

    const form = reactive({
      username: null,
      password: null,
      verify_code: null,
    });
    function IsEmailOrPhoneNumber(rule, value, callback) {
      if (
        !/^1[3456789]\d{9}$/.test(value) &&
        !/^[0-9a-zA-Z_.-]+[@][0-9a-zA-Z_.-]+([.][a-zA-Z]+){1,2}$/.test(value)
      ) {
        callback(new Error("必须是手机或邮箱号"));
      }
    }
    const rules = reactive({
      username: [
        { required: true, message: "请输入用户名", trigger: "blur" },
        { min: 6, max: 30, message: "6~30个字符", trigger: "blur" },
        { validator: IsEmailOrPhoneNumber, trigger: "blur" },
      ],
      password: [
        { required: true, message: "请输入密码", trigger: "blur" },
        { min: 6, max: 20, message: "6~20个字符", trigger: "blur" },
      ],
    });
    return {
      form,
      rules,
      loginFormRef,
      showLogin,
      showVerifyCode,
      loading,
      goBack,
      submitForm,
      cancelLogin,
    };
  },
};
</script>

<style>
.fitWidth {
  width: 30% !important;
  min-width: 400px !important;
  max-width: 500px !important;
}
</style>